#include "histogramwidget.h"

#define RGB_SPACE 0
#define YUV_SPACE 1

HistogramWidget::HistogramWidget(QWidget *parent) :
    QDockWidget(parent)
{
    QFrame *frame = new QFrame(this);
    QVBoxLayout *mainLayout = new QVBoxLayout(frame);
//    QLabel *histo = new QLabel(frame);
    scene = new QGraphicsScene(this);
    histoItem = scene->addPixmap(QPixmap());
    gView = new QGraphicsView(scene);

//    gView->fitInView(histoItem, Qt::KeepAspectRatio);
    gView->setMinimumSize(100, 60);

    spaceCombo = new QComboBox(frame);
    spaceCombo->addItem("RGB Space");
    spaceCombo->addItem("YUV Space");

    setWindowTitle(tr("Histogram"));
    mainLayout->addWidget(gView);
    mainLayout->addWidget(spaceCombo);
//    mainLayout->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Expanding));

    frame->setLayout(mainLayout);

    setWidget(frame);

    connect(spaceCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(changeSpace(int)));

//    setFloating(true);
}

void HistogramWidget::setHistograms(QImage rgbHisto, QImage yuvHisto)
{
    this->rgbHisto = rgbHisto;
    this->yuvHisto = yuvHisto;

    setHistogram(rgbHisto);
    spaceCombo->setCurrentIndex(RGB_SPACE);
}

void HistogramWidget::setImage(LImage *image)
{
    this->image = image;
    setHistograms(image->getHistogramImage(), image->getHistogramYUVImage());
}

void HistogramWidget::updateHistograms()
{
    if (image != NULL) {
        this->rgbHisto = image->getHistogramImage();
        this->yuvHisto = image->getHistogramYUVImage();
        changeSpace(spaceCombo->currentIndex());
    }
}

void HistogramWidget::clearHistograms()
{
    image = NULL;
    rgbHisto = QImage();
    yuvHisto = QImage();
    histoItem->setPixmap(QPixmap());
//    scene->removeItem(histoItem);
}

void HistogramWidget::setHistogram(QImage histo)
{
    histoItem->setPixmap(QPixmap::fromImage(histo));
    gView->fitInView(histoItem);
}

void HistogramWidget::changeSpace(int space)
{
    switch(space) {
    case RGB_SPACE:
        setHistogram(rgbHisto);
        break;
    case YUV_SPACE:
        setHistogram(yuvHisto);
        break;
    }
}

void HistogramWidget::resizeEvent(QResizeEvent*)
{
    gView->fitInView(histoItem);
}
